package cn.duapi.weblauncher;

import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.FragmentConfiguration;
import org.eclipse.jetty.webapp.MetaInfConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebInfConfiguration;
import org.eclipse.jetty.webapp.WebXmlConfiguration;

public class AppContextBuilder {

    WebAppContext webContext;

    public static final String CONTEXT_PATH = "/";

    private static final String DEFAULT_WEBAPP_PATH = "src/main/webapp";

    private static final String DEFAULT_WEBAPP_DESCRIPTOR = "src/main/webapp/WEB-INF/web.xml";

    private String webAppPath;

    private String webDescriptor;

    public WebAppContext buildWebAppContent(String contextPath) {

        webContext = new WebAppContext(getWebAppPath(), contextPath);

        // webContext.setContextPath("/");
        // 设置webapp的位置
        webContext.setResourceBase(getWebAppPath());

        webContext.setClassLoader(Thread.currentThread().getContextClassLoader());

        webContext.setDescriptor("weblauncher/webdefault.xml");
        // webContext.setDefaultsDescriptor("weblauncher/jetty-web.xml");

        webContext.setConfigurations(new Configuration[] { //
                new WebInfConfiguration()//
                , new WebXmlConfiguration()// scan WEB-INF/web....
                , new MetaInfConfiguration()
                , new EmbedMetaInfConfiguration()
                // 支持 web-fragment.xml
                , new FragmentConfiguration() //
        });

        // webContext.setParentLoaderPriority(true);

        return webContext;
    }

    public WebAppContext buildWebAppContent() {
        return this.buildWebAppContent(CONTEXT_PATH);
    }

    public String getWebDescriptor() {
        return webDescriptor == null ? DEFAULT_WEBAPP_DESCRIPTOR : webDescriptor;
    }

    public String getWebAppPath() {
        return webAppPath == null ? DEFAULT_WEBAPP_PATH : webAppPath;
    }

    public AppContextBuilder setWebAppPath(String webAppPath) {
        this.webAppPath = webAppPath;
        return this;
    }

    public AppContextBuilder setWebDescriptor(String webxml) {
        this.webDescriptor = webxml;
        return this;
    }

    /**
     * 
     * 
     * 
     * WebAppClassLoader classLoader = null; try { classLoader = new
     * WebAppClassLoader(webContext);
     * classLoader.addClassPath("target/classes");
     * classLoader.addClassPath("target/test-classes"); } catch (IOException e)
     * { e.printStackTrace(); } webContext.setClassLoader(classLoader);
     */

}
